package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.WemediaApplication;
import com.heima.wemedia.mapper.WemediaMapper;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    //拿到oss地址
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 分页条件查询自媒体文章列表
     *
     * @param dto 前端发送数据封装对象
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误!");
        }
        //判断每页条数和当前页码是否为空
        dto.checkParam();
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();

        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        // 发布时间区间查询
        wrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());

        // 当前自媒体人文章
        WmUser wmUser = WmThreadLocalUtils.getUser();
        //判读当前用户是否为null
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录!");
        }
        //用户id是否相等
        wrapper.eq(WmNews::getUserId, wmUser.getId());
        // 按照创建日期降序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);


        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3 执行查询
        IPage<WmNews> iPage = this.page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        //设置地址
        result.setHost(webSite);
        //返回结果
        return result;
    }


    /**
     * 自媒体文章-发布、修改、保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult submitNews(WmNewsDTO dto) {
        //将dto转化为wmnews对象
        //校验参数
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }
        //将dto属性拷贝到wmnews对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //type=-1 暂时设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //将集合转化为字符串,使用逗号拼接
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            String images = imagesToStrng(dto.getImages());
            wmNews.setImages(images);
        }
        //设置用户id
        wmNews.setUserId(wmUser.getId());
        //保存wmnews对象
        saveOrUpdateWmnews(wmNews);

        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }

        //保存文章内容或封面  素材的关联关系
        List<Map> mapList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> list = parseContentImage(mapList);
        //保存关联关系
        if (!CollectionUtils.isEmpty(list)) {
            saveRelativeInfo(list, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }

        //保存封面的关联关系
        saveRelativeInfoForCover(list, wmNews, dto);

        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 根据id查询文章
     *
     * @param id 文章id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "无效参数!");
        }
        //根据id查询文章
        //根据id查询文章
        WmNews wmNews = getById(id);
        //判断结果是否为null
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "找不到该文章,查询失败!");
        }
        //todo
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);

        //返回查询成功结果
        return result ;
    }

    /**
     * 根据id删除文章
     *
     * @param id 文章id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "删除失败!无效参数!");
        }
        //2.获取数据 通过id获取文章对象
        WmNews wmNews = getById(id);
        //判断对象是否为null
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "没有该文章,删除失败!");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已上架或已发布,无法删除!");
        }
        //4.去除素材与文章的关系 删除中间表信息
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        boolean result = removeById(id);
        //查看一下结果
        System.out.println(result);
        //6.返回删除成功
        return ResponseResult.okResult();
    }

    /**
     * 完成文章的上下架
     *
     * @param dto 封装的页面对象
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }
        //拿出上下架的状态
        Short enable = dto.getEnable();
        //判断状态是否异常
        if (enable == null || (!WemediaConstants.WM_NEWS_UP.equals(enable)
                && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            //不等于0或者1说明上下架状态异常
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态异常!");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        //判断对象是否为null
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "找不到该文章");
        }
        //3.判断文章是否发布
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章没有发布,不允许上下架!");
        }
        //4.修改文章状态，--同步到app端（后期做）
        //根据id修改文章状态值
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));

        //5. 上下架发送消息通知 用来同步后期搜索
        // 上架消息
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }

        //5.返回上下架成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    WmNewsMapper wmNewsMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断分页参数
        dto.checkParam();
        //记录当前页
        Integer page = dto.getPage();
        //设置分页起始索引 (page-1)*size
        dto.setPage((page - 1) * dto.getSize());

        //判断标题是否为空
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }

        //分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        //统计总条数
        long count = wmNewsMapper.findListCount(dto);
        //返回结果
        PageResponseResult result = new PageResponseResult(page, dto.getSize(), count, wmNewsVOList);
        result.setHost(webSite);
        return result;
    }


    @Autowired
    WemediaMapper wemediaMapper;

    /**
     * 根据文章id查询文章详情
     *
     * @param id 文章id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询作者信息
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wemediaMapper.selectById(wmNews.getUserId());
        }
        //封装vo信息返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        //复制属性
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        if (wmUser != null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        //设置地址
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //参数检查
        if (dto==null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章 根据id得到文章对象
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //检查文章状态 不能为发布状态 9
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已经发布了,无需进行人工审核!");
        }
        //修改文章状态
        wmNews.setStatus(status);
        //判断驳回理由是否为空
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        //修改
        boolean result = updateById(wmNews);
        //断点查看结果
        System.out.println(result);
        // 通知定时发布文章
        //获取发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        //获取当前时间
        long currentTime = System.currentTimeMillis();
        //发布时间减去当前时间
        long remainTime = publishTime - currentTime;

        //利用rabbitTemplate发送消息
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                (message) -> {                              // 延时消息 必设置
                    message.getMessageProperties()
                            .setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return message;   }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面的关联关系
     *
     * @param list   封面集合
     * @param wmNews 文章对象
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> list, WmNews wmNews, WmNewsDTO dto) {
        //去除封面集合
        List<String> images = dto.getImages();

        //判断type是否等于-1  ,生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            if (CollectionUtils.isEmpty(list)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (list.size() > 0 && list.size() <= 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = list.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = list.stream().limit(3).collect(Collectors.toList());
            }
        }
        if (!CollectionUtils.isEmpty(images)) {
            wmNews.setImages(imagesToStrng(images));
        }
        //修改wmnews
        boolean update = updateById(wmNews);
        //查看结果
        System.out.println(update);

        if (!CollectionUtils.isEmpty(images)) {
            //去除前缀
            images = images.stream()
                    .map(url -> url.replaceAll(webSite, ""))
                    //去重
                    .distinct()
                    //提取为集合
                    .collect(Collectors.toList());
            //保存关联的关联关系
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存关联关系
     *
     * @param list url集合
     * @param id   文章id
     * @param type 内容关联
     */
    private void saveRelativeInfo(List<String> list, Integer id, Short type) {
        //根据图片url列表 及登录用户id  查询素材ID
        Integer uid = WmThreadLocalUtils.getUser().getId();
        List<Integer> relationsIds = wmMaterialMapper.selectRelationsIds(list, uid);
        //检查id的数量小于url集合的size , 小于说明素材缺失 ,抛异常
        if (relationsIds.size() < list.size()) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存关联关系 foreach批量插入
        wmNewsMaterialMapper.saveRelations(relationsIds, id, type);
    }

    /**
     * 利用stream流将url集合返回
     *
     * @param mapList 封装的list集合
     * @return
     */
    private List<String> parseContentImage(List<Map> mapList) {
        return mapList.stream()
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                //取出url
                .map(map -> map.get("value").toString())
                //去除url
                .map(url -> url.replaceAll(webSite, ""))
                //去重
                .distinct()
                //提取
                .collect(Collectors.toList());

    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmnews(WmNews wmNews) {
        //信息补全
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //默认上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //判断是否存在id
        if (wmNews.getId() == null) {
            //没有id  save
            this.save(wmNews);
        } else {
            //有id修改
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     * 转换集合图片拼接格式
     *
     * @param images
     * @return
     */
    private String imagesToStrng(List<String> images) {
        String collect = images.stream()
                .map(url -> url.replaceAll(webSite, ""))
                .distinct()
                .collect(Collectors.joining(","));
        return collect;
    }
}